package com.hyt.it.ogt.ks.controller;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import com.hyt.it.ogt.ks.model.vo.paper.FilePicAnswerVO;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.hyt.common.apiInfor.ApiResponse;
import com.hyt.it.ogt.ks.config.ConfigManager;
import com.hyt.it.ogt.ks.config.KsBizRunTimeException;
import com.hyt.it.ogt.ks.enums.BizStatusCode;
import com.hyt.it.ogt.ks.model.entity.mongodb.CandidateAnswerLogBackup;
import com.hyt.it.ogt.ks.model.vo.PictureItemVO;
import com.hyt.it.ogt.ks.model.vo.paper.PictureItemInfo;
import com.hyt.it.ogt.ks.service.IPictureItemService;
import com.hyt.it.ogt.ks.service.Event.CandidateAnswerLogEvent;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiSort;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "21.图片题接口", value = "图片题接口")
@ApiSort(21)
@Slf4j
@RestController
@RequestMapping("/ks/picItem/")
public class PictureItemController {
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @Resource
    private ConfigManager configManager;
    @Resource
    private IPictureItemService iPictureItemService;

    @ApiOperation(value = "21.1 保存图片答案题作答答案", notes = "异常码：41210101-上传的答案图片超过最大限制,41210102-上传的图片非当前题," +
            "41210103-上传的图片参数不正确,41210104-图片保存失败,41210105-考生已交卷，不允许上传图片")
    @ApiOperationSort(1)
    @PostMapping("add")
    public ApiResponse add(@RequestBody @Valid PictureItemVO pictureItemVO, BindingResult bindingResult) {
        log.info("上传答案图片picItemUpload：{}", JSON.toJSONString(pictureItemVO));
        try{
            CandidateAnswerLogBackup logBackup = CandidateAnswerLogBackup.builder().examId(pictureItemVO.getExamId())
                    .candidateId(pictureItemVO.getCandidateId()).paperSort(pictureItemVO.getPaperSort())
                    .createDate(LocalDateTime.now()).requestJson(JSON.toJSONString(pictureItemVO)).build();
            applicationEventPublisher.publishEvent(new CandidateAnswerLogEvent(logBackup, null));
        } catch (Exception e) {
            log.error("保存答案失败saveQuestion:{}", e.getMessage());
        }
        try {
            if (bindingResult.hasErrors()) {
                log.info("上传答案图片picItemUpload参数错误:", bindingResult.getAllErrors());
                return ApiResponse.builder().code(BizStatusCode.PICTURE_ANSWER_ITEM_UPLOAD_PARAM_WRONG.getCode())
                        .data(bindingResult.getAllErrors()).build();
            }
            iPictureItemService.add(pictureItemVO);
        } catch (KsBizRunTimeException e) {
            return ApiResponse.builder().code(e.getCode()).data(e.getMessage()).build();
        } catch (Exception e) {
            log.error("# 上传答案图片保存失败", e);
            return ApiResponse.builder().code(BizStatusCode.PICTURE_ANSWER_ITEM_UPLOAD_ERROR.getCode())
                    .data(BizStatusCode.PICTURE_ANSWER_ITEM_UPLOAD_ERROR.getMsg()).build();
        }
        return ApiResponse.builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).build();
    }

    @ApiOperation(value = "21.2 获取小题答案图片")
    @ApiOperationSort(2)
    @GetMapping("get")
    public ApiResponse<FilePicAnswerVO> get(@RequestParam String examId, @RequestParam String candidateId, @RequestParam Integer paperSort,
                                                  @RequestParam String itemId) {
        FilePicAnswerVO picList = iPictureItemService.get(examId, candidateId, paperSort, itemId);
        log.info("获取小题答案图片picItemGet：{},{},{},{}", examId, candidateId, paperSort, itemId);
        return ApiResponse.<FilePicAnswerVO>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(picList).build();
    }

    @ApiOperation(value = "21.3 删除小题答案图片", notes = "41210301:考生已交卷，不允许删除图片")
    @ApiOperationSort(3)
    @DeleteMapping("del")
    public ApiResponse del(@RequestParam String examId, @RequestParam String candidateId, @RequestParam Integer paperSort,
                           @RequestParam String itemId, @RequestParam String picUrl) {
        log.info("获取小题答案图片picItemDel：{},{},{},{}", examId, candidateId, paperSort, itemId, picUrl);
        iPictureItemService.del(examId, candidateId, paperSort, itemId, picUrl);
        return ApiResponse.builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).build();
    }

    @ApiOperation(value = "21.4 获取小题答案图片题题干", response = PictureItemInfo.class)
    @ApiOperationSort(4)
    @GetMapping("getItemContent")
    public ApiResponse<PictureItemInfo> getItemContent(@RequestParam String examId, @RequestParam String candidateId,
                                                       @RequestParam Integer paperSort, @RequestParam String itemId) {
        log.info("获取小题答案图片题题干picItemGetItemContent：{},{},{},{}", examId, candidateId, paperSort, itemId);
        PictureItemInfo data = iPictureItemService.getItemInfo(examId, candidateId, paperSort, itemId);
        return ApiResponse.<PictureItemInfo>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(data).build();
    }

    @ApiOperation(value = "21.5 获取小题答案图片题图片数量限制上线", notes = "limitNum:上传文件数量限制，fileMaxSize：单个文件大小限制")
    @ApiOperationSort(5)
    @GetMapping("getLimitNum")
    public ApiResponse<Map<String, Object>> getLimitNum() {
        Map<String, Object> data = new HashMap<>();
        data.put("limitNum", configManager.getPictureItemLimit());
        data.put("fileMaxSize", configManager.getPictureItemMaxSize());
        return ApiResponse.<Map<String, Object>>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(data).build();
    }

    @ApiOperation(value = "21.6 是否允许上传答案图片（达到上线不允许传）", notes = "返回Boolean值")
    @ApiOperationSort(6)
    @GetMapping("allowUpload")
    public ApiResponse<Boolean> allowUpload(@RequestParam String examId, @RequestParam String candidateId,
                                            @RequestParam Integer paperSort, @RequestParam String itemId) {
        boolean flag = iPictureItemService.allowUpload(examId, candidateId, paperSort, itemId);
        return ApiResponse.<Boolean>builder().code(BizStatusCode.KS_SUCCESS_OK.getCode()).data(flag).build();
    }
}
